<template>
  <el-collapse v-model="collapse">
    <el-collapse-item title="分单" name="1">
      <el-form style="padding:10px 0" ref="refForm" label-width="100px" :model="stateForm" :rules="rulesForm">
        <el-form-item label="营销APP" prop="appId">
          <el-select v-model="stateForm.appId" clearable>
            <el-option v-for="item in productList" :key="item.appId" :label="item.appName"
                       :value="item.appId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="注册时间" prop="timeValue">
          <el-date-picker
              v-model="stateForm.timeValue"
              type="daterange"
              range-separator="~"
              :clearable="false"
              value-format="x"
              start-placeholder="开始时间"
              end-placeholder="结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label=" ">
          <el-button type="primary" @click="searchOrder" :loading="searchLoading">查询</el-button>
          <el-button @click="resetSearchOrder">重置</el-button>
        </el-form-item>
      </el-form>
    </el-collapse-item>
  </el-collapse>
  <Dialog v-model="distributionVisible" title="分单"  :footer="false" width="55%">
    <div style="margin-bottom:10px;text-align: right">
      <el-button type="primary" @click="orderDistribution('search')">所搜分配</el-button>
      <el-button type="primary" @click="orderDistribution('select')">所选分配</el-button>
    </div>
    <Table :tableData="distributionTableData" :tableColumn="distributionTableColumn" :page="distributionPage"
           :selection="true"
           v-model:selectRows="distributionRows"
           @handleCurrentChange="(val)=>{distributionPage.pageNum = val,searchOrder()}"
           @handleSizeChange="(val)=>{distributionPage.pageSize = val,searchOrder()}"
    />
    <Dialog :title="distributionType === 'search' ? '所搜分配' : '所选分配'" append-body
            @cancel="orderDistributionVisible = false"
            @confirm="orderDistributionConfirm"
            :confirm-loading="orderDistributionLoading"
            v-model="orderDistributionVisible">
      <el-form>
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="员工姓名">
              <el-input v-model="orderDistributionPage.name"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="账号">
              <el-input v-model="orderDistributionPage.account"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item>
              <el-button type="primary" @click="getMarketStaff">查询</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <Table :selection="true" v-model:selectRows="orderDistributionRows" :tableData="orderDistributionTableData"
             :page="false">
        <el-table-column label="员工姓名" prop="name" align="center"></el-table-column>
        <el-table-column label="账号" prop="account" align="center"></el-table-column>
      </Table>
    </Dialog>
  </Dialog>
</template>

<script>
import {onMounted, reactive, ref, toRefs} from "vue";
import {selectProductList, selectSystemUser} from "@/api";
import {
  fetchFlowMarketingConfig,
  flowMarketingSelect,
  flowMarketingSearch
} from '@/api/market'
import Dialog from "@/components/Dialog";
import {dateFormatTimeStamp} from "@/utils";
import {ElMessage} from "element-plus"

const distributionTableColumn = [
  {label: '姓名', prop: 'name', align: 'center', minWidth: 100},
  {label: '手机号码', prop: 'phone', align: 'center', minWidth: 150},
  {label: '注册时间', prop: 'registerTime', align: 'center', minWidth: 150},
]
export default {
  name: "dataUser",
  components: {Dialog},
  setup() {
    const refForm = ref(null)
    const state = reactive({
      collapse: ['1', '2'],
      productList: [],
      stateForm: {
        timeValue: null,
        appId: null,
      },
      rulesForm: {
        appId: [
          {required: true, message: '请选择APP', trigger: 'change'}
        ],

        timeValue: [
          {required: true, message: '请选择时间', trigger: 'change'}
        ],
      },
      searchLoading: false,
      distributionVisible: false,
      distributionPage: {
        pageSize: 10,
        pageNum: 1,
        total: 0
      },
      distributionRows: [],
      distributionTableData: [],
      orderDistributionTableData: [],
      orderDistributionRows: [],
      orderDistributionVisible: false,
      distributionType: null,
      orderDistributionPage: {
        pageSize: 10,
        pageNum: 1,
        total: 0
      },
      orderDistributionLoading: false
    })
    const methods = {
      getSelect() {
        selectProductList({status: 1}).then(res => {
          state.productList = res.data
        })
      },

      resetSearchOrder() {
        refForm.value.resetFields()
      },
      searchOrder() {
        refForm.value.validate(async v => {
          if (v) {
            const [datetimeStart, datetimeEnd] = dateFormatTimeStamp(state.stateForm.timeValue)
            const params = {
              channelId: state.stateForm.channelId,
              appId: state.stateForm.appId,
              datetimeStart, datetimeEnd,
              ...state.distributionPage
            }
            state.searchLoading = true
            const res = await fetchFlowMarketingConfig(params)
            if (res.code === 200) {
              const {list, total} = res.data
              state.distributionTableData = list
              state.distributionPage.total = total
              state.distributionVisible = true
            }
            state.searchLoading = false
          }
        })

      },
      orderDistribution(value) {
        if (value === 'select' && state.distributionRows.length === 0) {
          return this.$message.error('请选择订单')
        }
        state.distributionType = value
        state.orderDistributionVisible = true
        methods.getMarketStaff()
      },
      // 分配提交
      async orderDistributionConfirm() {
        if (state.orderDistributionRows.length === 0) return ElMessage.error('请选择员工')
        let params = {}
        if (state.distributionType === 'select') {
          // 所选
          params['flowSelectedDataParams'] = state.distributionRows
          params['systemUserIds'] = state.orderDistributionRows.map(item => item.systemUserId)
        } else {
          // 所搜
          const [datetimeStart, datetimeEnd] = dateFormatTimeStamp(state.stateForm.timeValue)
          params = {
            appId: state.stateForm.appId,
            datetimeStart, datetimeEnd,
            ...state.distributionPage,
            systemUserIds: state.orderDistributionRows.map(item => item.systemUserId)
          }
        }
        state.orderDistributionLoading = true
        const api = (params) => state.distributionType === 'select' ? flowMarketingSelect(params) : flowMarketingSearch(params)
        const res = await api(params)
        if (res.code === 200) {
          ElMessage.success('操作成功')
          state.orderDistributionVisible = false
          methods.searchOrder()
        }
        state.orderDistributionLoading = false
      },
      async getMarketStaff() {
        const res = await selectSystemUser({marketingSwitch: 1, ...state.orderDistributionPage,status:1})
        if (res.code === 200) {
          state.orderDistributionTableData = res.data
        }
      }
    }
    onMounted(() => {
      methods.getSelect()
    })
    return {
      refForm,
      distributionTableColumn,
      ...methods,
      ...toRefs(state)
    }
  }
}
</script>

<style scoped>
::v-deep .el-collapse-item__header {
  background-color: #ebeef5;
  padding: 0 15px;
}
</style>
